/*
 * @Author: intellectual-seeker 3336339701@qq.com
 * @Date: 2025-03-24 16:54:48
 * @LastEditors: intellectual-seeker 3336339701@qq.com
 * @LastEditTime: 2025-04-03 21:26:54
 * @FilePath: /code/lesson25/processpool/task.hpp
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#include <iostream>
#include <unistd.h>

using namespace std;

typedef void(*work_t)(int);
typedef void(*task_t)(int, pid_t);

void PrintLog(int fd, pid_t pid)
{
    cout << "sub process: " << pid << ", fd:" << fd << ", task is: print log task\n" << endl;
}

void ReloadConf(int fd, pid_t pid)
{
    cout << "sub process: " << pid << ", fd:" << fd << ", task is: reload conf task\n" << endl;
}

void ConnectMysql(int fd, pid_t pid)
{
    cout << "sub process: " << pid << ", fd:" << fd << ", task is: connect mysql task\n" << endl;
}

task_t tasks[3] = {PrintLog, ReloadConf, ConnectMysql};

uint32_t NextTask()
{
    return rand() % 3;
}

void worker(int fd)
{
    //从fd: 0中读取数据
    while(true)
    {
        uint32_t command_code = 0;
        ssize_t n = read(0, &command_code, sizeof(command_code));//scanf

        //cout << "sizeof(command_code): " << sizeof(command_code) << " command_code: " << command_code << " n: " << n << endl;
        if(n == sizeof(command_code))
        {
            if(command_code >= 3) continue;
            tasks[command_code](fd, getpid());
        }
        else if(n == 0)
        {
            cout << "sub process: " << getpid() << " quit now..." << endl;
            break;
        }
        //cout << "I am worker: " << getpid() << endl;
    }
}